package com.chukun.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author chukun
 *  AIO服务端
 */
public class AIOServer {

    private final int port;

    public static void main(String[] args) {
        new AIOServer(8888);
    }

    public AIOServer(int port) {
        this.port = port;
        listen();
    }

    private void listen() {
        try {
            ExecutorService executorService = Executors.newCachedThreadPool();
            AsynchronousChannelGroup threadGroup =
                    AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
            AsynchronousServerSocketChannel server = AsynchronousServerSocketChannel.open(threadGroup);
            server.bind(new InetSocketAddress(port));
            System.out.println("服务启动，端口: "+port);

            server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
                final ByteBuffer buffer = ByteBuffer.allocate(1024);
                @Override
                public void completed(AsynchronousSocketChannel result, Object attachment) {
                    System.out.println("I/O操作成功，开始获取数据");
                    try{
                        buffer.clear();
                        result.read(buffer).get();
                        buffer.flip();
                        result.write(buffer).get();
                        buffer.flip();
                    }catch (Exception e) {
                        System.out.println(e.getMessage());
                    }finally {
                        try {
                            result.close();
                        }catch (Exception e) {
                            System.out.println(e.getMessage());
                        }
                    }

                    System.out.println("操作成功");

                }

                @Override
                public void failed(Throwable exc, Object attachment) {
                    System.out.println("I/O操作失败: "+exc);
                }
            });

            try {
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
            }catch (InterruptedException e) {
                System.out.println(e.getMessage());
            }
        }catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
